<template>
	<div>
		<el-header :class="header">
			<div class="link-list">
				<img :class="logoClass" src="../assets/logo_shallow.png" />
				<span
					v-for="item in menuItems"
					:key="item.name"
					:class="['link-item', $route.path == item.path ? 'link-item__active' : '']"
					@click="gotoPage(item)"
					>{{ item.label }}</span
				>
				<span
					:class="['link-item', $route.path == loginItem.path ? 'link-item__active' : '']"
					@click="isAuthenticated ? logout() : gotoPage(loginItem)"
					>{{ loginItem.label }}</span
				>	




			</div>

			<div v-if="isAuthenticated" class="ava-username" @click="goPersonalCenter">
				<span class="avatar-wrapper">
					<el-avatar 
						:size="40" 
						:src="userAvatar" 
						@error="handleAvatarError">
						<img src="../assets/default-avatar.svg"/>
					</el-avatar>
					<span class="username">{{ username || '未登录' }}</span>
				</span>
			</div>


		</el-header>
	</div>
</template>

<script scoped>
import store from '../store';
import axios from '../config/http'
export default {
	name: 'Header',
	mounted() {
		this.changeHeader();
		this.checkAuthentication()
		this.getUserInfo()
		if(this.$route.path === '/test'){
			this.deep = false
		}
		
	},
	data() {
		return {
			deep: false,
			selectedOption:'',  //绑定下拉框的值
			username:'',
			userAvatar: '',
			menuItems: [
				{
					label: '首页',
					name: 'Index',
					path: '/'
				},
				{
					label: '新闻动态',
					name: 'News',
					path: '/news'
				},
				{
					label: '项目介绍',
					name: 'Projects',
					path: '/projects'
				},
				{
					label: '实验室团队',
					name: 'Teams',
					path: '/teams'
				},
				{
					label: '知识宝库',
					name: 'Learning',
					path: '/learning'
				},


				{
					label: '生活视窗',
					name: 'Test',
					path: '/post'
				},
				{
					label: '加入我们',
					name: 'JoinUs',
					path: '/joinUs'
				}
			],
			isAuthenticated:false
		};
	},
	computed: {
		header() {
			return ['header', this.deep ? 'header-deep' : ''];
		},
		logoClass() {
			return this.deep ? 'logo' : 'logo-shallow';
		},
		// logoUrl() {
		// 	// return this.deep ? require('@/assets/logo.png') : require('@/assets/logo_shallow.png');
		// },
		itemClass() {
			return;
		},
		loginItem() {
			// 根据是否认证返回不同的菜单项配置
			return this.isAuthenticated 
				? ''
				: { label: '登录/注册', name: 'Login', path: '/login' };
		}
	},
	watch:{
		selectedOption(newValue){
			if(newValue === 'logout'){
				this.logout()
			}
		}
	},
	methods: {
		checkAuthentication(){
			const token = store.getters.token  //token
			if(token){
				this.username = store.getters.username
				// console.log(this.username);
				this.getUserInfo()
				
			}
			this.isAuthenticated = !! token  // 如果token存在，则设置为true
		},
		changeHeader() {
			window.addEventListener('scroll', () => {
				let scrollTop = document.documentElement.scrollTop;
				// 根据滚动距离判断是否Header变成深色模式
				if (scrollTop > 100) {
					this.deep = true;
				} else {
					this.deep = false;
				}
			});
		},
		gotoPage(item) {
			if (this.$route.path != item.path) this.$router.push(item.path);
		},
		async logout(){
			await axios.post('/as/accounts/logout')
			this.$store.dispatch('user/loginOut')
			this.$message.success('退出成功')
			this.isAuthenticated = false;
			this.$router.push('/login');
		},
		// 获取用户信息
		async getUserInfo() {
			try {
				const result = await axios.get('/us/user/current')
				if (result.data.code === 200 && result.data.data?.data) {
					const userInfo = result.data.data.data
					this.username = userInfo.username
					// 处理头像URL
					if (userInfo.image) {
						this.userAvatar = userInfo.image.startsWith('http') 
							? userInfo.image 
							: `${process.env.VUE_APP_BASE_API}${userInfo.image}`
					}
				}
			} catch (error) {
				console.error('获取用户信息失败:', error)
			}
		},
		goPersonalCenter(){
			this.$router.push('/personal')
		},
		handleAvatarError(event) {
			event.target.src = require('../assets/default-avatar.svg');
		}
	}
};
</script>

<style lang="less" scoped>
/* 字体大小 font-size */
@fs-base: 16px;
@fs-large: 24px;
@fs-small: 14px;
@fs-smaller: 12px;

.header {
	display: flex;
	width: 100%;
	align-items: center;
	background-color: transparent;
	padding: 30px 0;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 1000;
	color: #fff;
	font-size: 14px;
	font-family: 'simhei';
	
	transition: all 1s ease-in-out;

	&-deep {
		background-color: #fff;
		color: #000;
	}

	.logo {
		height: 45px;
	}

	.logo-shallow {
		height: 60px;
	}

	.link-list {
		display: flex;
		width: 100%;
		gap: 50px;
		padding: 0 20px;
		align-items: center;
		.link-item {
			padding: 10px 0;
			border-bottom: solid 2px transparent;
			transition: all 0.3s ease-in-out;

			&:hover {
				cursor: pointer;
				border-bottom: solid 2px;
			}

			&__active {
				border-bottom: solid 2px;
			}
		}
		
	
	}

	.ava-username {
    display: flex;
    align-items: center;
    gap: 10px; // 设置元素间的间距，可根据实际情况调整
		line-height: 15px;
    img {
        width: 40px; 
        height: 40px;
        border-radius: 50%;
        background-color: #ccc;
    }
	.infoName{
		font-size: 22px;
		font-weight: 600;
		color: #333;
	}

   
}

.avatar-wrapper {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 0 15px;
    height: 100%;
    transition: background-color 0.3s;
}

.avatar-wrapper:hover {
    background-color: rgba(0, 0, 0, 0.025);
}

.username {
    margin-left: 12px;
    font-size: 15px;
    color: #606266;
}

.el-avatar {
    background-color: #edf6fa;
    border: 1px solid #e6e6e6;
    width: 40px !important;
    height: 40px !important;
}

.ava-username {
    display: flex;
    align-items: center;
    height: 100%;
}

	@media screen and (max-width: 768px) {
		.link-list {
			gap: 10px;
			padding: 0 10px;
			font-size: @fs-smaller;

			.logo {
				height: 30px;
			}

			.logo-shallow {
				height: 45px;
			}
		}
	}
}
</style>